#!/bin/bash

DAEMONIZE=false
for option in "$@"; do
  case "$option" in
    -d|--daemonize)
      DAEMONIZE=true
      ;;
  esac
done

IDX_DIR=$(cd "$(dirname "$0")";pwd)

# check if current system is mac
if [[ $(uname) == "Darwin" ]]; then
  JAVA_CMD=$(which java)
else
  JAVA_CMD=$(update-alternatives --list java | tail -1)
fi
IDX_JAVA_OPTS="--enable-preview -Xms4G -Xmx4G -XX:+UseG1GC --add-modules java.se --add-exports java.base/jdk.internal.ref=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/sun.nio.ch=ALL-UNNAMED --add-opens java.management/sun.management=ALL-UNNAMED --add-opens jdk.management/com.sun.management.internal=ALL-UNNAMED"
IDX_CLASSPATH="$IDX_DIR/lib/*"
IDX_TMP_DIR="-D'java.io.tmpdir=$IDX_DIR/temp'"

if [[ $DAEMONIZE = false ]]; then
  exec \
    $JAVA_CMD \
    $IDX_TMP_DIR \
    $IDX_JAVA_OPTS \
    -cp "$IDX_CLASSPATH" \
    com.gitee.gateway.core.Server \
    "$@"
else
  exec \
    $JAVA_CMD \
    $IDX_TMP_DIR \
    $IDX_JAVA_OPTS \
    -cp "$IDX_CLASSPATH" \
    com.gitee.gateway.core.Server \
    "$@" &
  retval=$?
  pid=$!
  [ $retval -eq 0 ] || exit $retval
  if ! echo $pid > $IDX_DIR/temp/pid ; then
    exit 1
  fi
  exit 0
fi

exit $?
